package dse.messages.multiversion;

import dse.*;
import dse.messages.Message;
import dse.messages.MessageHandler;
import dse.messages.MessageSender;
import dse.messages.MessageType;

public class RequestLatestShareV2MessageHandler extends MessageSender implements
		MessageHandler {

	private DataObject dobj;
	private VersionReader reader;
	
	public RequestLatestShareV2MessageHandler(Experiment experiment, DataObject dobj, VersionReader reader)
	{
		super(experiment);
		
		this.dobj = dobj;
		this.reader = reader;
	}
	
	@Override
	public boolean acceptMessage(Message message) {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public void messageInterupted(ExperimentRecorder recorder, Message message,
			double time) {
		// TODO Auto-generated method stub
		recorder.debug(this, "msgIntrpt: " + message, time);
		reader.readVersion(recorder, message.to(), null, time);
	}

	@Override
	public void messageReceived(ExperimentRecorder recorder, Message message,
			double time) {
		// TODO Auto-generated method stub
		recorder.debug(this, "msgRcvd: " + message, time);
		if (message.messageType() != MessageType.RequestLatestShareV2) {
			recorder.warn(
					"RequestLatestShareV2MessageHandler recieved " + 
					message.messageType() + " message."
					);
			return;
		}			
		// What do we know about the share?
		Node receiver = message.to();
		
		// Does the receiver have the share?
		DataShare share = receiver.getDataShare(dobj);
		if (share != null)
		{
			// Then we need to send a new message BACK (thats why to and from
			// are reversed!
			Message m = super.createShareDownloadMessage(receiver, message.from(), dobj, share.getLatest(), 
					message.purpose(), reader);
			recorder.debug(this, "new msg: " + m, time);
			experiment.messageQueue().enqueueMessage(m, time);
		}
		else
			this.messageInterupted(recorder, message, time);
	}
}
